package com.cskaoyan.service;


import com.cskaoyan.bean.bo.AuthLoginBo;
import com.cskaoyan.bean.bo.AuthRegisterBO;
import com.cskaoyan.bean.bo.AuthResetBO;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.beanwx.vo.AuthLoginVo;
import com.cskaoyan.dao.*;
import com.cskaoyan.exception.UserLoginException;
import com.cskaoyan.realm.MallToken;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.sql.SQLOutput;
import java.sql.Time;
import java.util.Date;
import java.util.List;

/**
 * @author: 刘森飚
 * @class: UserServiceImpl
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserAddressMapper userAddressMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    FootprintMapper footprintMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    FeedbackMapper feedbackMapper;



    @Override
    public UserListVo queryUsersData(Integer page, Integer limit, String sort, String order,
                                     String username, String mobile) {

        PageHelper.startPage(page, limit);
        //username = "test1" nickname like 测试用户
        //每个service的方法都来创建example对象
        UserExample userExample = new UserExample();
        //排序信息
        userExample.setOrderByClause(sort+" "+order);
        UserExample.Criteria criteria = userExample.createCriteria();
//        criteria.andUsernameEqualTo("test1").andNicknameLike("%测试用户%");
        System.err.println("username"+username );
        System.err.println("mobile"+mobile );
        if (username != null&&!"".equals(username)){
            criteria.andUsernameLike("%"+username+"%");
        }
        if (mobile != null&&!"".equals(mobile)){
            criteria.andMobileLike("%"+mobile+"%");
        }

        List<User> users =userMapper.selectByExample(userExample);

        //可以获得分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);

        long total = userPageInfo.getTotal();
        UserListVo userVo = new UserListVo();
        userVo.setTotal((int)total);
        userVo.setItems(users);

        return userVo;
    }

    @Override
    public UserAddressListVo1 queryAddressesData(Integer page, Integer limit, String sort, String order, String name, Integer userId) {
        PageHelper.startPage(page, limit);

        UserAddressExample userAddressExample = new UserAddressExample();

        UserAddressExample.Criteria criteria = userAddressExample.createCriteria();

        if (name!=null&&!"".equals(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if (userId!=null&&!"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        List<UserAddress> userAddresses = userAddressMapper.selectByExample(userAddressExample);
        System.out.println(userAddresses);
        PageInfo<UserAddress> userPageInfo = new PageInfo<>(userAddresses);
        long total = userPageInfo.getTotal();
        UserAddressListVo1 userAddressListVo11 = new UserAddressListVo1();
       userAddressListVo11.setItems(userAddresses);
        userAddressListVo11.setTotal((int)total);

        return userAddressListVo11;
    }

    @Override
    public UserCollectVo querryCollectData(Integer page, Integer limit, String sort, String order, Integer userId, Integer valueId) {
        PageHelper.startPage(page, limit);
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        if (userId!=null&&!"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        if (valueId!=null&&!"".equals(valueId)){
            criteria.andValueIdEqualTo(valueId);
        }
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        PageInfo<Collect> userPageInfo = new PageInfo<>(collects);
        long total = userPageInfo.getTotal();
        UserCollectVo userCollectVo = new UserCollectVo();
        userCollectVo.setItems(collects);
        userCollectVo.setTotal((int)total);
        return userCollectVo;
    }

    @Override
    public UserFootPrintVo querryFootPrintData(Integer page, Integer limit, String sort, String order, Integer userId, Integer goodsId) {
        PageHelper.startPage(page, limit);
        FootprintExample footprintExample = new FootprintExample();
        FootprintExample.Criteria criteria = footprintExample.createCriteria();
        if (userId!=null&&!"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        if (goodsId!=null&&!"".equals(goodsId)){
            criteria.andGoodsIdEqualTo(goodsId);
        }
        List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
        UserFootPrintVo userFootPrintVo = new UserFootPrintVo();
        PageInfo<Footprint> userPageInfo = new PageInfo<>(footprints);
        long total = userPageInfo.getTotal();
        userFootPrintVo.setItems(footprints);
        userFootPrintVo.setTotal((int)total);
        return  userFootPrintVo;
    }

    @Override
    public UserHistoryVo querryHistoryData(Integer page, Integer limit, String sort, String order, String keyword, Integer userId) {
        PageHelper.startPage(page, limit);
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        if (userId!=null&&!"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        if (keyword!=null&&!"".equals(keyword)){
            criteria.andKeywordLike("%"+keyword+"%");
        }
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        UserHistoryVo userHistoryVo = new UserHistoryVo();
        PageInfo<SearchHistory> userPageInfo = new PageInfo<>(searchHistories);
        long total = userPageInfo.getTotal();
        userHistoryVo.setItems(searchHistories);
        userHistoryVo.setTotal((int)total);
        return userHistoryVo;
    }

    @Override
    public UserFeedBackVo querryFeedBackData(Integer page, Integer limit, String sort, String order, String username, Integer id) {
        PageHelper.startPage(page, limit);
        FeedbackExample feedbackExample = new FeedbackExample();
        FeedbackExample.Criteria criteria = feedbackExample.createCriteria();
        if (id!=null&&!"".equals(id)){
            criteria.andIdEqualTo(id);
        }
        if (username!=null&&!"".equals(username)){
            criteria.andUsernameLike("%"+username+"%");
        }
        List<Feedback> feedbacks = feedbackMapper.selectByExample(feedbackExample);
        UserFeedBackVo userFeedBackVo = new UserFeedBackVo();
        PageInfo<Feedback> userPageInfo = new PageInfo<>(feedbacks);
        long total = userPageInfo.getTotal();
        userFeedBackVo.setItems(feedbacks);
        userFeedBackVo.setTotal((int)total);
        return userFeedBackVo;
    }

    @Override
    public User queryUserById(int userId) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);

        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) {
            return null;
        }
        return users.get(0);
    }

    @SneakyThrows
    @Override
    public AuthRegisterVo insertUser(AuthRegisterBO authRegisterBO) {
        User user = new User();
        user.setAddTime(new Date());
        user.setUsername(authRegisterBO.getUsername());
        user.setPassword(authRegisterBO.getPassword());
        user.setLastLoginTime(new Date());
        user.setWeixinOpenid(authRegisterBO.getWxCode());
        user.setNickname(authRegisterBO.getUsername());
        user.setMobile(authRegisterBO.getMobile());
        user.setUpdateTime(new Date());
        user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        userMapper.insertSelective(user);

        AuthRegisterVo authRegisterVo = new AuthRegisterVo();
        authRegisterVo.setUserInfo(new RegisterUserInfoVO(authRegisterBO.getUsername(),authRegisterBO.getUsername(),user.getAvatar()));

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new MallToken(authRegisterBO.getUsername(), authRegisterBO.getPassword(),"wx"));
        } catch (Exception e) {
            throw new UserLoginException(null,"用户名或密码不正确");
        }
        String sessionID = (String) subject.getSession().getId();

        authRegisterVo.setToken(sessionID);
        return authRegisterVo;
    }

    @Override
    public void updateUser(AuthResetBO authResetBO) {
        User user = new User();
        user.setPassword(authResetBO.getPassword());

        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(authResetBO.getMobile());
        userMapper.updateByExampleSelective(user,userExample);
    }


}
